package pack2_factory;
import java.lang.reflect.Constructor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class Singleton{
    private Singleton(){}

    public void doSomething(){
        System.out.println("I am doing something...");
    }
}

class SingletonFactory{
    private static Singleton singleton;

    public static synchronized Singleton create_singleton(){
        // synchronized(singleton){ 同步代码块会报错Caused by: java.lang.NullPointerException，主要是singleton为null无法加锁
        try{
            if(singleton == null){
                //先获取Singleton的类对象，再获取Singleton的私有构造函数
                Class clz = Class.forName(Singleton.class.getName());
                Constructor constructor = clz.getDeclaredConstructor();
                constructor.setAccessible(true);  //设置私有无参构造是可访问的
                singleton = (Singleton)constructor.newInstance();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        // }
        return singleton;
    }

    public static Singleton getSingleton(){
        singleton = create_singleton();
        return singleton;
    }
}

public class code002_SingletonFactory {
    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(10));
        int minister_count = 10;
        for (int i = 0; i < minister_count; i++) {
            executor.execute(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    Singleton singleton = SingletonFactory.getSingleton();
                    System.out.println(singleton);
                }
            });
        }
        executor.shutdown();
    }
}
